<template>
<div class="grid-page-background"><!-- 单一根，指令才能生效，必须 v-modaldrag --->
  <div class="divide-line"></div>
  <el-row align="middle">
    <el-col :span="8"><div class="grid-title"><label>项目信息列表<!--功能名称--></label></div></el-col>
    <el-col :span="16"><div class="grid-title-tip"><!-- 功能描述 --></div></el-col>
  </el-row>
  <div class="divide-line">
  </div>
<vxe-grid  v-bind="gridOptions.gridProps"  ref="projectGrid"  @sortChange="($event:any)=>gridOptions.changeSort($event)">
    <template #toolbar_buttons>
      <el-space size="large">
      <query-field :filter-column="nameColumnFilter" @change="getProjectList"/> <!-- 项目简称 查询条件 -->
      
      <el-space size="small">
      <el-button type="primary" @click="getProjectList" :icon="Search" size="medium">查询</el-button>
      <el-button @click="resetQueryFilters" :icon="Reset" size="medium">重置</el-button>
      <dayu-auth-button @click="addProjectBtnClick" :icon="Plus" size="medium" :authTag="actionState.authTag" :lockState="actionState.lockState" :masterLockState="actionState.masterLockState">新增</dayu-auth-button>
      </el-space>
      </el-space>
    </template>

    <template #top>
      <div class="grid-stats"><!-- 统计数据栏 -->
        <el-space>
          <InfoFilled twoToneColor="#1890FF" style="padding-left: 5px;"/>
          <span>共查询到 {{gridOptions.pager.totalRows}} 条记录</span>
          <div class="v-divider-w1" style="height:30px"></div>          
          <span>项目简称：</span>
          <span>记录条数：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.nameRowsCount || 0 }}</el-tag></span>          <div class="v-divider-w1" style="height:30px"></div>          
          <span>合同金额：</span>
          <span>合计：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.contractAmountSum || 0 }}</el-tag>元</span>，
          <span>平均值：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.contractAmountAvg || 0 }}</el-tag>元</span>          <div class="v-divider-w1" style="height:30px"></div>          
          <span>项目评分：</span>
          <span>合计：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.projectScoreSum || 0 }}</el-tag></span>，
          <span>平均值：<el-tag color="#e62" style="color:#fff; font-weight: bold;">{{ statData.total.projectScoreAvg || 0 }}</el-tag></span>        </el-space>
      </div>
    </template>
    <template #pager>
      <dayu-pager :pager="gridOptions.pager" @change="onPagerChange"></dayu-pager>
    </template>
    <template #projectKindColumn="{ row }">  <!-- 项目类型 字段自定义显示 -->
      <dayu-dropdown :row=row labelProp="projectKindCaption" valueProp="projectKind" :options="projectKindItems" @change="changeProjectKind" :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState"></dayu-dropdown>
    </template>
    <template #districtCodeColumn="{ row }">  <!-- 所在行政区 字段自定义显示 -->
      <dayu-dropdown :row=row labelProp="districtCodeCaption" valueProp="districtCode" ></dayu-dropdown>
    </template>
    <template #projectStatusColumn="{ row }">  <!-- 项目状态 字段自定义显示 -->
      <dayu-dropdown :row=row labelProp="projectStatusCaption" valueProp="projectStatus" :options="projectStatusItems" @change="changeProjectStatus" :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState"></dayu-dropdown>
    </template>
    <template #operationColumn="{ row }">
      <el-space size="small" class="operationColumn">
        <dayu-auth-button @click="editProjectBtnClick(row.id)" type="primary" size="mini" :icon="Edit" plain :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState">编辑</dayu-auth-button>
        <dayu-auth-button @click="deleteProjectBtnClick(row.id, row.name)" type="danger" size="mini" :icon="Delete" plain :authTag="actionState.authTag" :lockState="row.rowLock" :masterLockState="actionState.masterLockState">删除</dayu-auth-button>
        <dayu-data-lock :onChangeState="projectRowLockStateChange" size="mini" :dataId="row.id" :authTag="actionState.authTag" :masterLockState="actionState.masterLockState" v-model:lockState="row.rowLock"/>
      </el-space>
    </template>
  </vxe-grid>
  <dayu-form-dialog title="项目信息-属性编辑" :formModal="projectFormModal" :width="800" @ok='projectFormModalHandleOk'>
    <ProjectForm ref="projectForm" :id="projectFormModal.id"/>
  </dayu-form-dialog>
</div>
</template>

<script lang="ts" setup>

/*
 * @author: user
 * @date: 2021-11-24 14:45:24
 * @template: dayu-code-builder
*/

import { ref, reactive, onMounted, computed, watchEffect } from 'vue'
import { Edit, Delete, Search, Plus, Download as Export, InfoFilled, Refresh as Reset } from '@element-plus/icons';
import { VxeGridProps } from 'vxe-table'
import store from '@/store'
import { FormModal, IForm } from '@/common/FormModal'
import { FilterValue, FilterColumn, FilterColumns, QueryConfig, ListBO, buildDefaultVxeGridOptions, myutil} from '@/common/dayu-common'
import { ActionState } from '@/common/AuthState'
import { mycolors } from '@/common/colors';
import ProjectForm from './ProjectForm.vue'
import { projectService, ProjectStats, ProjectStatData } from '@/api/demo/ProjectService';

/** 授权和锁定状态 */
const actionState = ref(new ActionState(true, true, 0xFFFF, 0, 0));

const projectGrid = ref();
const projectForm = ref();
const projectFormModal = reactive(new FormModal());//表单弹窗

//表格变量
const gridOptions = reactive(buildVxeGridOptions());//vxe-grid 的参数，包括表格数据
const aggregationData = reactive({aggregations:[]});//表格数据的统计值

//定义查询项
const nameColumnFilter = reactive(new FilterColumn('项目简称', new FilterValue('name', 'string', 'like', false, false ), "")); // 项目简称 
//查询项集合
const filterColumns = new FilterColumns([
    nameColumnFilter
]);



/** 整理统计数据 */
const statData = computed(() => {
  let statData_ = {
      total: new ProjectStatData
      , projectKind_1:new ProjectStatData, projectKind_2:new ProjectStatData, projectKind_3:new ProjectStatData
      , districtCode_1:new ProjectStatData, districtCode_2:new ProjectStatData, districtCode_3:new ProjectStatData};
  if(aggregationData.aggregations && aggregationData.aggregations.length > 0){
    for(let i=0; i<aggregationData.aggregations.length; i++){
      let row : ProjectStats = aggregationData.aggregations[i] as ProjectStats;
      if(row.aggregateGroupName == 'total'){
        statData_.total.nameRowsCount = row.nameRowsCount;
        statData_.total.contractAmountSum = row.contractAmountSum;
        statData_.total.contractAmountAvg = row.contractAmountAvg;
        statData_.total.projectScoreSum = row.projectScoreSum;
        statData_.total.projectScoreAvg = row.projectScoreAvg;
      }
      if(row.aggregateGroupName == 'projectKind'){
        if(row.projectKind == '1'){  //此处由模板自动生成，需要根据实际字典项的代码值进行修改。
          statData_.projectKind_1.nameRowsCount = row.nameRowsCount;
          statData_.projectKind_1.contractAmountSum = row.contractAmountSum;
          statData_.projectKind_1.contractAmountAvg = row.contractAmountAvg;
          statData_.projectKind_1.projectScoreSum = row.projectScoreSum;
          statData_.projectKind_1.projectScoreAvg = row.projectScoreAvg;
        }else if(row.projectKind == '2'){
          statData_.projectKind_2.nameRowsCount = row.nameRowsCount;
          statData_.projectKind_2.contractAmountSum = row.contractAmountSum;
          statData_.projectKind_2.contractAmountAvg = row.contractAmountAvg;
          statData_.projectKind_2.projectScoreSum = row.projectScoreSum;
          statData_.projectKind_2.projectScoreAvg = row.projectScoreAvg;
        }else if(row.projectKind == '3'){
           statData_.projectKind_3.nameRowsCount = row.nameRowsCount;
           statData_.projectKind_3.contractAmountSum = row.contractAmountSum;
           statData_.projectKind_3.contractAmountAvg = row.contractAmountAvg;
           statData_.projectKind_3.projectScoreSum = row.projectScoreSum;
           statData_.projectKind_3.projectScoreAvg = row.projectScoreAvg;
        }
      }
      if(row.aggregateGroupName == 'districtCode'){
        if(row.districtCode == '1'){  //此处由模板自动生成，需要根据实际字典项的代码值进行修改。
          statData_.districtCode_1.nameRowsCount = row.nameRowsCount;
          statData_.districtCode_1.contractAmountSum = row.contractAmountSum;
          statData_.districtCode_1.contractAmountAvg = row.contractAmountAvg;
          statData_.districtCode_1.projectScoreSum = row.projectScoreSum;
          statData_.districtCode_1.projectScoreAvg = row.projectScoreAvg;
        }else if(row.districtCode == '2'){
          statData_.districtCode_2.nameRowsCount = row.nameRowsCount;
          statData_.districtCode_2.contractAmountSum = row.contractAmountSum;
          statData_.districtCode_2.contractAmountAvg = row.contractAmountAvg;
          statData_.districtCode_2.projectScoreSum = row.projectScoreSum;
          statData_.districtCode_2.projectScoreAvg = row.projectScoreAvg;
        }else if(row.districtCode == '3'){
           statData_.districtCode_3.nameRowsCount = row.nameRowsCount;
           statData_.districtCode_3.contractAmountSum = row.contractAmountSum;
           statData_.districtCode_3.contractAmountAvg = row.contractAmountAvg;
           statData_.districtCode_3.projectScoreSum = row.projectScoreSum;
           statData_.districtCode_3.projectScoreAvg = row.projectScoreAvg;
        }
      }
    }
  }
  return statData_;
});


/** 构造 vxe-grid 的参数 */
function buildVxeGridOptions(){
  let gridOptions = buildDefaultVxeGridOptions();//构造vxe-grid的默认属性
  let gridProps : VxeGridProps = { //本页面定制的属性
      border:"inner",
    columns: [
      { type: 'seq', title:'序号', width: 50, align:'center', fixed:'left'},
      { field: 'name', title: '项目简称',sortable:true, width: 150, align:'left', fixed:'left'      ,showOverflow: true},
      { field: 'fullName', title: '项目全称',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'code', title: '项目编码',sortable:false, width: 180, align:'left'      ,showOverflow: true},
      { field: 'address', title: '项目地点',sortable:false, width: 180, align:'left'      ,showOverflow: true},
      { field: 'lng', title: '经度',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'lat', title: '纬度',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'projectKind', title: '项目类型',sortable:true, width: 100, align:'center', slots:{default:'projectKindColumn'}      ,showOverflow: true},
      { field: 'salesManager', title: '销售经理',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'districtCode', title: '所在行政区',sortable:true, width: 100, align:'center', slots:{default:'districtCodeColumn'}      ,showOverflow: true},
      { field: 'projectManager', title: '项目经理',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'initialDate', title: '立项日期',sortable:true, width: 100, align:'center'      ,showOverflow: true},
      { field: 'bidDate', title: '中标日期',sortable:true, width: 100, align:'center'      ,showOverflow: true},
      { field: 'contractAmount', title: '合同金额(元)',sortable:true, width: 100, align:'right', formatter:({ cellValue })=> cellValue?'￥'+cellValue:'-'      ,showOverflow: true},
      { field: 'projectMonths', title: '项目周期(月)',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'projectStatus', title: '项目状态',sortable:true, width: 100, align:'center', slots:{default:'projectStatusColumn'}      ,showOverflow: true},
      { field: 'projectScore', title: '项目评分',sortable:true, width: 100, align:'right'      ,showOverflow: true},
      { field: 'projectOwner', title: '业主单位',sortable:false, width: 180, align:'left'      ,showOverflow: true},
      { field: 'linkMan', title: '联系人姓名',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'linkPhone', title: '联系人电话',sortable:true, width: 150, align:'left'      ,showOverflow: true},
      { field: 'abort', title: '是否中止',sortable:true, width: 100, align:'center'      ,showOverflow: true}
      ,{ title:'操作', width: 240, align:'center', slots:{default:'operationColumn'}, fixed:'right'}
    ]
  };
  gridOptions.pager.pageSize = 10;
  Object.assign(gridOptions.gridProps, gridProps);

  //排序事件的回调函数
  gridOptions.onSortChanged = function(field:string, order:string){
    console.log(`sort field:${field}, order:${order}`);
    getProjectList();
  }
  return gridOptions;
}

/** 分页组件事件回调（PageIndex或者PageSize发生变化时） */
const onPagerChange = (page: number, pageSize: number) =>{
  getProjectList();
}

/**从服务端获取数据（根据新的参数）*/
async function getProjectList(){
  
  gridOptions.gridProps.loading = true;//正在加载
  try{
    let response : any = await projectService.getProjectExListAndStats(filterColumns.getQueryFilters(),
        new QueryConfig(gridOptions.pager.pageIndex, gridOptions.pager.pageSize, gridOptions.sorter.field, gridOptions.sorter.order));
    let listBO = response.data as ListBO;
    actionState.value.setActionState(listBO.authTag, listBO.lockState, listBO.lockState);
    gridOptions.gridProps.data = listBO.items;//表格数据
    aggregationData.aggregations = listBO.aggregations;
    let currPager:any = listBO.pager;
    gridOptions.gridProps.seqConfig = {startIndex: currPager.startRows};//重新设置行号的起始值
    gridOptions.pager.totalRows = currPager.totalRows as number;//重新设置总记录数
    projectKindItems.value = listBO.codeTypes["projectKind"];
    projectStatusItems.value = listBO.codeTypes["projectStatus"];
  }finally{
    gridOptions.gridProps.loading = false;
  }
}

/** 重置查询条件 */
function resetQueryFilters(){
  filterColumns.reset();
  getProjectList();
}

/**cell编辑按钮点击事件*/
async function editProjectBtnClick(id : number) {
  projectFormModal.showModal(id);//显示表单对话框
}


/**表单【确定】按钮点击事件*/
async function projectFormModalHandleOk() {
  let response = await projectFormModal.submit(projectForm.value as IForm);
  console.log("after ok button clicked:");
  console.log(response);
  getProjectList();
}

/**cell上的删除按钮事件*/
async function deleteProjectBtnClick(id : number, name : string){
  myutil.confirmForDelete(`确认删除 ${name} 吗?`).then(async () => {
      await projectService.deleteProject(id);
      getProjectList();
  });  
}


const projectKindItems = ref(new Array<{code:string, name:string}>());//字典值
async function changeProjectKind(row:any, projectKind :any){//当通过下拉菜单更改项目类型时
  await projectService.updateProp(row.id, "projectKind", projectKind);
 
  //let response : any = await projectService.getProject(row.id);//如果此属性的改变，涉及到统计数据的改变，则需要注释掉此段代码，使用下面的getProjectList()调用。
  //let project = response.data;
  //row.projectKind = project.projectKind;
  //row.projectKindCaption = project.projectKindCaption;
  getProjectList();//如果此属性的改变，涉及到统计数据的改变，则需要调用此函数，把上面的getProject函数注释掉。
}
const projectStatusItems = ref(new Array<{code:string, name:string}>());//字典值
async function changeProjectStatus(row:any, projectStatus :any){//当通过下拉菜单更改项目状态时
  await projectService.updateProp(row.id, "projectStatus", projectStatus);
 
  let response : any = await projectService.getProject(row.id);//如果此属性的改变，涉及到统计数据的改变，则需要注释掉此段代码，使用下面的getProjectList()调用。
  let project = response.data;
  row.projectStatus = project.projectStatus;
  row.projectStatusCaption = project.projectStatusCaption;
  //getProjectList();//如果此属性的改变，涉及到统计数据的改变，则需要调用此函数，把上面的getProject函数注释掉。
}

async function projectRowLockStateChange(id:number, lockState:number){
  try{
    let response = await projectService.changeLockState(id, lockState);
    return Promise.resolve(lockState);
  }catch(ex:any){
    return Promise.reject(ex);
  }
}

/**添加按钮点击事件*/
async function addProjectBtnClick() {
  projectFormModal.showModal();//显示表单对话框
}

/** 主区域的高度 */
const mainHeight = ref(800);
/** 监听浏览器窗口大小（监听vuex store里的值，在App.vue中监听window.size事件时会更改） */
watchEffect(() =>{
  mainHeight.value = store.state.windowClient.height - store.state.topBarHeight - store.state.bottomBarHeight - 80;
  gridOptions.gridProps.height = mainHeight.value;
})

onMounted(() => {
  getProjectList();
});

</script>

<style scoped>

</style>